<template>
  <view>
    <view class="bottom-shop-one">
      <view class="bottom-shop-image">
        <image :src="storeInfo.imgUrl"></image>
      </view>
      <view class="bottom-shop-desc">
        <text style="font-size: 18px; font-weight: bold">{{
          storeInfo.name
        }}</text>
        <br />
        <text style="font-size: 15px; font-weight: bold"
          >月售: {{ storeInfo.sales }}</text
        >
        <text style="font-size: 15px; font-weight: bold"
          >起送: {{ storeInfo.expressLimit }}</text
        >
        <text style="font-size: 15px; font-weight: bold"
          >基础运费: {{ storeInfo.expressPrice }}</text
        >
        <br />
        <text style="font-size: 15px; color: red">{{ storeInfo.slogan }}</text>
      </view>
    </view>

    <view class="content">
      <view class="left-list">
        <view class="allshop" @click="requestProcutsAll" ref="allshop">
          全部商品
        </view>
        <view class="seckill" @click="requestProcutsSeckill" ref="seckill">
          秒杀
        </view>
        <view class="freshfruit" @click="requestProcutsFruit" ref="freshfruit">
          新鲜水果
        </view>
      </view>
      <view class="right-list">
        <view class="shop-item" v-for="(item, index) in products" :key="index">
          <image :src="item.imgUrl"></image>
          <view class="shop-item-desc">
            <text>{{ item.name }}</text
            ><br />
            <text> 月售{{ item.sales }}件</text><br />
            <text style="padding-right: 10px">￥{{ item.price }}</text>
            <text style="color: gray; text-decoration: line-through"
              >￥{{ item.oldPrice }}</text
            >
            <button
              class="shop-item-button"
              @click="addToCart(item)"
              type="primary"
            >
              加入购物车
            </button>
          </view>
        </view>
      </view>
    </view>

    <view style="clear: both"></view>
    <view id="bottom-cart" @click="openCart">
      <image src="../../static/imgs/assets/basket.png" />
      <view class="bottom-cart-num" v-if="cartTotal.quantity > 0">
        {{ cartTotal.quantity }}
      </view>
      <text class="bottom-cart-total">
        总价: ￥{{ cartTotal.amount.toFixed(2) }}
      </text>
    </view>
    <!-- 购物车弹框 -->
    <view v-if="showCartModal" class="cart-modal">
      <view class="modal-content">
        <view class="modal-header">
          <text class="modal-title">购物车</text>
          <text @click="closeCart" class="close-btn">×</text>
        </view>

        <!-- 购物车内容 -->
        <scroll-view class="cart-list" scroll-y>
          <view
            v-for="(item, index) in cartItems"
            :key="index"
            class="cart-item"
          >
            <image class="item-image" :src="item.imgUrl"></image>
            <view class="item-details">
              <text class="item-name">{{ item.name }}</text>
              <view class="item-info">
                <text class="item-price">￥{{ item.price }}</text>
                <text class="item-quantity">x{{ item.quantity || 1 }}</text>
              </view>
            </view>
          </view>
        </scroll-view>

        <view class="modal-footer">
          <text class="total-text">总计：￥{{ totalPrice.toFixed(2) }}</text>
          <button class="checkout-btn" @click="gotoConfirmOrder" v-if="cartTotal.quantity > 0">去结算</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
<<<<<<< HEAD
import config from "../../config";
import { v4 as uuidv4 } from "uuid";

export default {
    data() {
        return {
            data: [],
            products: [],
            storeInfo: {},
            currentShopId: null,
            showCartModal: false, // 控制弹框显示
            cartItems: [], // 购物车列表数据
            totalPrice: 0, // 总价
            cartTotal: {
                quantity: 0, // 商品总数量
                amount: 0.0, // 商品总金额
            },
        };
    },
    onLoad(options) {
        const storeId = options.id;
        this.currentShopId = storeId;
        this.fetchStoreDetail(storeId);
        this.requestProcutsAll();
        this.fetchCartData();
    },
    methods: {
        fetchCartData() {
            const userId = uni.getStorageSync('ID');
            const shopId = this.currentShopId;
            uni.request({
                url: config.URL + "/cart",
                method: 'GET',
                data: {
                    userId,  // 当前用户 id
                    shopId   // 当前店铺 id
                },
                success: (res) => {
                    const cartItems = res.data;

                    // 计算总数量和总金额
                    this.cartTotal = cartItems.reduce(
                        (acc, item) => {
                            acc.quantity += item.quantity || 1;
                            acc.amount += item.price * (item.quantity || 1);
                            return acc;
                        },
                        { quantity: 0, amount: 0 }
                    );

                    // 保留两位小数
                    this.cartTotal.amount = Number(this.cartTotal.amount.toFixed(2));
                },
                fail: (error) => {
                    console.error('获取购物车数据失败:', error);
                }
            });
        },
        selectShop(shopId) {
            this.currentShopId = shopId;
            console.log("currentshopid" + this.currentShopId);
            this.fetchStoreDetail(shopId);
            this.requestProcutsAll();
        },

        fetchStoreDetail(storeId) {
            uni.request({
                url: config.URL + "/shop",
                method: 'GET',
                data: {
                    _id: storeId,
                },
                success: (res) => {
                    this.storeInfo = res.data[0];
                    console.log(res.data[0]);
                },
                fail: (error) => {
                    console.error('获取店铺详情失败:', error);
                }
            });
        },
        requestProcutsAll() {
            console.log("requestProductsAll");
            uni.request({
                url: config.URL + "/productsAll",
                method: 'GET',
                data: {
                    shopId: this.currentShopId
                },
                success: (res) => {
                    this.products = res.data;
                    this.$nextTick(() => {
                        console.log("this.$refs.allshop:", this.$refs.allshop);
                        if (this.$refs.allshop) {
                            this.$refs.allshop.$el.style.backgroundColor = "white";
                            this.$refs.seckill.$el.style.backgroundColor = "gainsboro";
                            this.$refs.freshfruit.$el.style.backgroundColor = "gainsboro";
                        }
                    });
                },
                fail: (error) => {
                    console.error('获取全部商品数据失败:', error);
                }
            });
        },
        requestProcutsSeckill() {
            console.log("requestProductsSeckill");
            uni.request({
                url: config.URL + "/productsSeckill",
                method: 'GET',
                data: {
                    shopId: this.currentShopId
                },
                success: (res) => {
                    this.products = res.data;
                    this.$nextTick(() => {
                        if (this.$refs.seckill) {
                            this.$refs.seckill.$el.style.backgroundColor = "white";
                            this.$refs.allshop.$el.style.backgroundColor = "gainsboro";
                            this.$refs.freshfruit.$el.style.backgroundColor = "gainsboro";
                        }
                    });
                },
                fail: (error) => {
                    console.error('获取秒杀商品数据失败:', error);
                }
            });
        },
        requestProcutsFruit() {
            console.log("requestProductsFruit");
            uni.request({
                url: config.URL + "/productsFruit",
                method: 'GET',
                data: {
                    shopId: this.currentShopId
                },
                success: (res) => {
                    this.products = res.data;
                    this.$nextTick(() => {
                        if (this.$refs.freshfruit) {
                            this.$refs.freshfruit.$el.style.backgroundColor = "white";
                            this.$refs.allshop.$el.style.backgroundColor = "gainsboro";
                            this.$refs.seckill.$el.style.backgroundColor = "gainsboro";
                        }
                    });
                },
                fail: (error) => {
                    console.error('获取新鲜水果商品数据失败:', error);
                }
            });
        },

       addToCart(item) {
           const date = new Date();
           const year = date.getFullYear();
           const month = date.getMonth() + 1; // 月份从 0 开始，所以需要加 1
           const day = date.getDate();
           const hours = date.getHours();
           const minutes = date.getMinutes();
           const seconds = date.getSeconds();
       
           // 格式化为 xxxx 年 x 月 x 日 x 时 x 分 x 秒
           const time = `${year}年${month}月${day}日 ${hours}时${minutes}分${seconds}秒`;
       
           const userId = uni.getStorageSync('ID');
           const shopId = this.currentShopId;
       
           // 自定义生成 UUID 的函数
          function customUuidv4() {
              const array = new Uint8Array(16);
              uni.getRandomValues(array);
              array[6] = (array[6] & 0x0f) | 0x40;
              array[8] = (array[8] & 0x3f) | 0x80;
              return Array.from(array, (v) => v.toString(16).padStart(2, '0')).join('')
                 .replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, '$1-$2-$3-$4-$5');
          }
       
           const uniqueId = customUuidv4();
           const itemWithId = {
              ...item,
               time,
               uniqueId,
               userId,  // 添加用户 id
               shopId,   // 添加店铺 id
           };
       
           uni.request({
               url: config.URL + "/cart", // 确保 URL 正确
               method: 'POST',
               data: itemWithId,
               success: () => {
                   // 添加成功后立即更新数据
                   this.fetchCartData();
       
                   uni.showToast({
                       title: "已加入购物车",
                       icon: "success",
                   });
               },
               fail: (error) => {
                   console.error('添加商品到购物车失败:', error);
               }
           });
       },
        openCart() {
            this.showCartModal = true;
            uni.request({
                url: config.URL + "/cart",
                method: 'GET',
                data: {
                    shopId: this.currentShopId,
                    userId: uni.getStorageSync('ID')
                },
                success: (res) => {
                    this.cartItems = res.data;

                    // 计算最新统计
                    this.cartTotal = res.data.reduce(
                        (acc, item) => {
                            acc.quantity += item.quantity || 1;
                            acc.amount += item.price * (item.quantity || 1);
                            console.log("acc", acc);
                            this.totalPrice = acc.amount;
                            return acc;
                        },
                        { quantity: 0, amount: 0 }
                    );

                    this.showCartModal = true;
                },
                fail: (error) => {
                    console.error('打开购物车获取数据失败:', error);
                }
            });
        },

        closeCart() {
            this.showCartModal = false;
        },
        gotoConfirmOrder() {
            uni.switchTab({
                url: '/pages/cart/index'
            });
        }
    },
};
    
</script>
	<style scoped>
	/* 调整弹框内容高度 */
	.modal-content {
	  background: white;
	  width: 100%;
	  max-height: 70vh; /* 增加高度适应图片 */
	  border-radius: 20px 20px 0 0;
	  padding: 20px;
	}
	
	/* 调整滚动区域高度 */
	.cart-list {
	  max-height: calc(60vh - 100px); /* 预留操作按钮空间 */
	  margin-bottom: 15px;
	}
	.cart-item {
	  display: flex;
	  align-items: center;
	  padding: 10px 0;
	  border-bottom: 1px solid #eee;
	}
	
	.item-image {
	  width: 60px;
	  height: 60px;
	  border-radius: 8px;
	  margin-right: 15px;
	}
	
	.item-details {
	  flex: 1;
	}
	
	.item-name {
	  font-size: 14px;
	  margin-bottom: 5px;
	  display: block;
	}
	
	.item-info {
	  display: flex;
	  align-items: center;
	}
	/* 购物车弹框样式 */
	.cart-modal {
	  position: fixed;
	  top: 0;
	  left: 0;
	  width: 100%;
	  height: 100%;
	  background: rgba(0, 0, 0, 0.5);
	  z-index: 1000;
	}
	
	.modal-content {
	  background: white;
	  width: 90%;
	  max-height: 70vh;
	  position: absolute;
	  bottom: 60px; /* 改为底部栏高度 */
	  border-radius: 20px 20px 0 0;
	  padding: 20px;
	  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
	}
	
	.modal-header {
	  display: flex;
	  justify-content: space-between;
	  align-items: center;
	  margin-bottom: 15px;
	}
	
	.modal-title {
	  font-size: 18px;
	  font-weight: bold;
	}
	
	.close-btn {
	  font-size: 24px;
	  padding: 10px;
	}
	
	.cart-list {
	  max-height: 40vh;
	  margin-bottom: 15px;
	}
	
	.cart-item {
	  display: flex;
	  justify-content: space-between;
	  padding: 10px 0;
	  border-bottom: 1px solid #eee;
	}
	
	.item-price {
	  color: red;
	  margin-right: 15px;
	}
	
	.modal-footer {
	  display: flex;
	  justify-content: space-between;
	  align-items: center;
	}
	
	.checkout-btn {
	  background: #007aff;
	  color: white;
	  border-radius: 20px;
	  padding: 0 30px;
	}
	#bottom-cart {
	  position: fixed;
	  bottom: 0;
	  left: 0;
	  width: 100%;
	  height: 60px;
	  background-color: white;
	  z-index: 999;
	  display: flex;
	  align-items: center;
	}
	
	#bottom-cart image {
	  width: 40px; /* 调整图标大小 */
	  height: 40px;
	  margin-left: 20px;
	}
	
	.bottom-cart-num {
	  min-width: 20px;
	  height: 20px;
	  padding: 0 5px;
	  background-color: red;
	  border-radius: 10px;
	  color: white;
	  text-align: center;
	  line-height: 20px;
	  font-size: 12px;
	  position: absolute;
	  left: 50px;
	  top: 5px;
	  display: flex;
	  align-items: center;
	  justify-content: center;
	}
	
	.bottom-cart-total {
	  margin-left: auto; /* 右对齐 */
	  margin-right: 20px;
	  font-weight: bold;
	  font-size: 16px;
	}
	.shop-item-button {
	  height: 30px;
	  width: 100px;
	  font-size: 13px;
	}
	.shop-item {
	  width: 100%;
	  height: 150px;
	}
	.shop-item image {
	  width: 70px;
	  height: 70px;
	  padding: 10px;
	  float: left;
	}
	.shop-item-desc {
	  padding-top: 10px;
	}
	.allshop,
	.seckill,
	.freshfruit {
	  width: 100%;
	  height: 50px;
	  line-height: 50px;
	  text-align: center;
	  font-size: 18px;
	}
	.content {
	}
	.left-list {
	  width: 30%;
	  height: 700px;
	  background-color: gainsboro;
	  float: left;
	}
	.right-list {
	  width: 70%;
	  height: 700px;
	
	  float: right;
	}
	
	.bottom-shop-one,
	.bottom-shop-two {
	  width: 100%;
	  height: auto;
	  display: flex;
	  align-items: center;
	  padding: 10px 0;
	  border-bottom: 1px solid #000;
	}
	.bottom-shop-image {
	  width: 80px;
	  height: 80px;
	  border-radius: 50%;
	  margin-right: 10px;
	}
	.bottom-shop-image image {
	  width: 100%;
	  height: 100%;
	}
	.bottom-shop-desc {
	  flex: 1;
	}
	</style>
	
=======
import axios from "axios";
import { v4 as uuidv4 } from "uuid";

export default {
  data() {
    return {
      data: [],
      products: [],
      storeInfo: {},
      currentShopId: null,
      showCartModal: false, // 控制弹框显示
      cartItems: [], // 购物车列表数据
      totalPrice: 0, // 总价
      cartTotal: {
        quantity: 0, // 商品总数量
        amount: 0.0, // 商品总金额
      },
    };
  },
  onLoad(options) {
    const storeId = options.id;
    this.currentShopId = storeId;
    this.fetchStoreDetail(storeId);
    this.requestProcutsAll();
    this.fetchCartData();
  },
  methods: {
      




    fetchCartData() {
        const userId = uni.getStorageSync('ID');
        const shopId = this.currentShopId;
      axios
        .get("https://67f78cbf7719dfcd4b4774b8.hz-iframe-svc.simplelab.cn/cart", {
          params: { 
      userId,  // 当前用户 id
      shopId   // 当前店铺 id
    }
        })
        .then((res) => {
          const cartItems = res.data;

          // 计算总数量和总金额
          this.cartTotal = cartItems.reduce(
            (acc, item) => {
              acc.quantity += item.quantity || 1;
              acc.amount += item.price * (item.quantity || 1);
              return acc;
            },
            { quantity: 0, amount: 0 }
          );

          // 保留两位小数
          this.cartTotal.amount = Number(this.cartTotal.amount.toFixed(2));
        });
    },
    selectShop(shopId) {
      this.currentShopId = shopId;
      console.log("currentshopid" + currentShopId);
      this.fetchStoreDetail(shopId);
      this.requestProcutsAll();
    },

    fetchStoreDetail(storeId) {
      axios
        .get("https://67f78cbf7719dfcd4b4774b8.hz-iframe-svc.simplelab.cn/shop", {
          params: {
            _id: storeId,
          },
        })
        .then((res) => {
          this.storeInfo = res.data[0];
          console.log(res.data[0]);
        });
    },
    requestProcutsAll() {
      console.log("requestProductsAll");
      axios
        .get("https://67f78cbf7719dfcd4b4774b8.hz-iframe-svc.simplelab.cn/productsAll", {
          params: { shopId: this.currentShopId },
        })
        .then((res) => {
          this.products = res.data;
          this.$nextTick(() => {
            console.log("this.$refs.allshop:", this.$refs.allshop);
            if (this.$refs.allshop) {
              this.$refs.allshop.$el.style.backgroundColor = "white";
              this.$refs.seckill.$el.style.backgroundColor = "gainsboro";
              this.$refs.freshfruit.$el.style.backgroundColor = "gainsboro";
            }
          });
        });
    },
    requestProcutsSeckill() {
      console.log("requestProductsSeckill");
      axios
        .get("https://67f78cbf7719dfcd4b4774b8.hz-iframe-svc.simplelab.cn/productsSeckill", {
          params: { shopId: this.currentShopId },
        })
        .then((res) => {
          this.products = res.data;
          this.$nextTick(() => {
            if (this.$refs.seckill) {
              this.$refs.seckill.$el.style.backgroundColor = "white";
              this.$refs.allshop.$el.style.backgroundColor = "gainsboro";
              this.$refs.freshfruit.$el.style.backgroundColor = "gainsboro";
            }
          });
        });
    },
    requestProcutsFruit() {
      console.log("requestProductsFruit");
      axios.get("https://67f78cbf7719dfcd4b4774b8.hz-iframe-svc.simplelab.cn/productsFruit", {
          params: { shopId: this.currentShopId },
        })
        .then((res) => {
          this.products = res.data;
          this.$nextTick(() => {
            if (this.$refs.freshfruit) {
              this.$refs.freshfruit.$el.style.backgroundColor = "white";
              this.$refs.allshop.$el.style.backgroundColor = "gainsboro";
              this.$refs.seckill.$el.style.backgroundColor = "gainsboro";
            }
          });
        });
    },

    addToCart(item) {
      const date = new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1; // 月份从0开始，所以需要加1
  const day = date.getDate();
  const hours = date.getHours();
  const minutes = date.getMinutes();
  const seconds = date.getSeconds();

  // 格式化为xxxx年x月x日 x时x分x秒
  const time = `${year}年${month}月${day}日 ${hours}时${minutes}分${seconds}秒`;

  const userId = uni.getStorageSync('ID');
  const shopId = this.currentShopId;
  const uniqueId = uuidv4();
  const itemWithId = {
    ...item,
    time,
    uniqueId,
    userId,  // 添加用户 id
    shopId,   // 添加店铺 id
  };

      axios.post("https://67f78cbf7719dfcd4b4774b8.hz-iframe-svc.simplelab.cn/cart", itemWithId).then(() => {
        // 添加成功后立即更新数据
        this.fetchCartData();
      
        uni.showToast({
          title: "已加入购物车",
          icon: "success",
        });
      });
    },
    openCart() {
      this.showCartModal = true;
      axios
        .get("https://67f78cbf7719dfcd4b4774b8.hz-iframe-svc.simplelab.cn/cart", {
          params: {
             shopId: this.currentShopId ,

          userId: uni.getStorageSync('ID')
          
          },
        })
        .then((res) => {
          this.cartItems = res.data;

          // 计算最新统计
          this.cartTotal = res.data.reduce(
            (acc, item) => {
              acc.quantity += item.quantity || 1;
              acc.amount += item.price * (item.quantity || 1);
                console.log("acc",acc);
                this.totalPrice = acc.amount;
              return acc;
               
            },
            { quantity: 0, amount: 0 }
          );
       
          this.showCartModal = true;
        });
    },

    closeCart() {
      this.showCartModal = false;
    },
    gotoConfirmOrder() {
      uni.switchTab({
        url: '/pages/cart/index'
      });
    }
  },
};
>>>>>>> a951c251b8a727f3f517ca1a33bd5d47f7de5751
</script>
<style scoped>
/* 调整弹框内容高度 */
.modal-content {
  background: white;
  width: 100%;
  max-height: 70vh; /* 增加高度适应图片 */
  border-radius: 20px 20px 0 0;
  padding: 20px;
}

/* 调整滚动区域高度 */
.cart-list {
  max-height: calc(60vh - 100px); /* 预留操作按钮空间 */
  margin-bottom: 15px;
}
.cart-item {
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.item-image {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  margin-right: 15px;
}

.item-details {
  flex: 1;
}

.item-name {
  font-size: 14px;
  margin-bottom: 5px;
  display: block;
}

.item-info {
  display: flex;
  align-items: center;
}
/* 购物车弹框样式 */
.cart-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1000;
}

.modal-content {
  background: white;
  width: 90%;
  max-height: 70vh;
  position: absolute;
  bottom: 60px; /* 改为底部栏高度 */
  border-radius: 20px 20px 0 0;
  padding: 20px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.modal-title {
  font-size: 18px;
  font-weight: bold;
}

.close-btn {
  font-size: 24px;
  padding: 10px;
}

.cart-list {
  max-height: 40vh;
  margin-bottom: 15px;
}

.cart-item {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.item-price {
  color: red;
  margin-right: 15px;
}

.modal-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.checkout-btn {
  background: #007aff;
  color: white;
  border-radius: 20px;
  padding: 0 30px;
}
#bottom-cart {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 60px;
  background-color: white;
  z-index: 999;
  display: flex;
  align-items: center;
}

#bottom-cart image {
  width: 40px; /* 调整图标大小 */
  height: 40px;
  margin-left: 20px;
}

.bottom-cart-num {
  min-width: 20px;
  height: 20px;
  padding: 0 5px;
  background-color: red;
  border-radius: 10px;
  color: white;
  text-align: center;
  line-height: 20px;
  font-size: 12px;
  position: absolute;
  left: 50px;
  top: 5px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.bottom-cart-total {
  margin-left: auto; /* 右对齐 */
  margin-right: 20px;
  font-weight: bold;
  font-size: 16px;
}
.shop-item-button {
  height: 30px;
  width: 100px;
  font-size: 13px;
}
.shop-item {
  width: 100%;
  height: 150px;
}
.shop-item image {
  width: 70px;
  height: 70px;
  padding: 10px;
  float: left;
}
.shop-item-desc {
  padding-top: 10px;
}
.allshop,
.seckill,
.freshfruit {
  width: 100%;
  height: 50px;
  line-height: 50px;
  text-align: center;
  font-size: 18px;
}
.content {
}
.left-list {
  width: 30%;
  height: 700px;
  background-color: gainsboro;
  float: left;
}
.right-list {
  width: 70%;
  height: 700px;

  float: right;
}

.bottom-shop-one,
.bottom-shop-two {
  width: 100%;
  height: auto;
  display: flex;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #000;
}
.bottom-shop-image {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  margin-right: 10px;
}
.bottom-shop-image image {
  width: 100%;
  height: 100%;
}
.bottom-shop-desc {
  flex: 1;
}
</style>
